<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Friend
 *
 * @author tuancasi
 */
class Friend extends CActiveRecord {

    public $friendName = '';

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return User the static model class
     */
    public static function model($className = __CLASS__) {
	return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
	return '{{friends}}';
    }

    public function rules() {
	return array(
	    array('friend_id, user_id, friend_user_id, time_created, friendName', 'safe')
	);
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
	// NOTE: you may need to adjust the relation name and the related
	// class name for the relations automatically generated below.
	return array(
	    'user' => array(self::BELONGS_TO, 'User', 'friend_user_id')
	);
    }

    /**
     * Accept friend
     */
    public static function insertFriend($userId, $friendUserId, $is_read = 0) {
	$time = date('Y-m-d h:i:s', time());
	Yii::app()->db->createCommand("INSERT INTO {{friends}}(`user_id`, `friend_user_id`,`is_read`, `time_created`) VALUES(" . $userId . ", " . $friendUserId . ", " . $is_read . " ,'" . $time . "')")->execute();
	//only contain id friend
	$aIdFriends = Yii::app()->cache->get('aIdFriend' . $userId);
	if ($aIdFriends !== false) {
	    $aIdFriends = Yii::app()->cache->delete('aIdFriend' . $userId);
	}
	//only contain id friend
	$aIdFriends = Yii::app()->cache->get('aIdFriend' . $friendUserId);
	if ($aIdFriends !== false) {
	    $aIdFriends = Yii::app()->cache->delete('aIdFriend' . $friendUserId);
	}


	//only contain username and email of friend
	$friends = Yii::app()->cache->get('aFriends' . $userId);
	if ($friends !== false) {
	    $aIdFriends = Yii::app()->cache->delete('aFriends' . $userId);
	}
	//only contain username and email of friend
	$friends = Yii::app()->cache->get('aFriends' . $friendUserId);
	if ($friends !== false) {
	    $aIdFriends = Yii::app()->cache->delete('aFriends' . $friendUserId);
	}
    }

    /**
     * 
     * @return \CActiveDataProvider
     */
    public function search($id) {
	// Warning: Please modify the following code to remove attributes that
	// should not be searched.

	$criteria = new CDbCriteria;
	$criteria->with = array("user");
	$criteria->alias = 't';
	$criteria->addCondition('t.user_id=' . $id);
	$criteria->compare('user.username', $this->friendName, true);

	return new CActiveDataProvider($this, array(
	    'criteria' => $criteria,
	    'pagination' => array(
		'pageSize' => param('pageSize')
	    ),
	    'sort' => array(
		'defaultOrder' => array(
		    'time_created' => CSort::SORT_DESC
		)
	    )
	));
    }

    /**
     * get friend has accept invitation recently
     * @param type $userId
     * @return type array
     */
    public static function getAcceptFriend($userId) {
	$data = Yii::app()->db->createCommand(
			"SELECT COUNT(friend_id) as num_friend_added 
			FROM {{friends}}
			WHERE is_read = " . NOT_READ . " and user_id = " . $userId)
		->queryRow();
	return $data['num_friend_added'];
    }

    /**
     * set have checked list friend
     * @param type $userId
     * @return type array
     */
    public static function updateChecked($userId) {
	$data = Yii::app()->db->createCommand(
			"UPDATE {{friends}} SET is_read=" . READED . "
			WHERE is_read = " . NOT_READ . " and user_id = " . $userId)
		->execute();
    }

    /**
     * delete friend
     */
    public static function deleteFriend($userId, $friendUserId) {
	Yii::app()->db->createCommand('
	    DELETE FROM {{friends}} 
	    WHERE (user_id=' . $userId . ' and friend_user_id=' . $friendUserId . ') 
		OR (user_id=' . $friendUserId . ' and friend_user_id=' . $userId . ')')->execute();

	$aIdFriends = Yii::app()->cache->get('aIdFriend' . $userId);
	if ($aIdFriends !== false) {
	    $aIdFriends = Yii::app()->cache->delete('aIdFriend' . $userId);
	}
	$aIdFriends = Yii::app()->cache->get('aIdFriend' . $friendUserId);
	if ($aIdFriends !== false) {
	    $aIdFriends = Yii::app()->cache->delete('aIdFriend' . $friendUserId);
	}


	//only contain username and email of friend
	$friends = Yii::app()->cache->get('aFriends' . $userId);
	if ($friends !== false) {
	    $aIdFriends = Yii::app()->cache->delete('aFriends' . $userId);
	}
	$friends = Yii::app()->cache->get('aFriends' . $friendUserId);
	if ($friends !== false) {
	    $aIdFriends = Yii::app()->cache->delete('aFriends' . $friendUserId);
	}
    }

    public static function getIdsFriend($id) {

	$aIdFriends = Yii::app()->cache->get('aIdFriend' . $id);
	if ($aIdFriends === false) {
	    $aIdFriends = array();
	    $aFriends = Yii::app()->db->createCommand('SELECT * FROM {{friends}} WHERE user_id=' . $id)->queryAll();
	    foreach ($aFriends as $aFriends) {
		$aIdFriends[] = $aFriends['friend_user_id'];
	    }
	    Yii::app()->cache->set('aIdFriend' . $id, $aIdFriends);
	}
	return $aIdFriends;
    }

    /**
     * get all friends of user (information about friend)
     * 
     * @return array 
     */
    public static function getFriends($id) {

	$friends = Yii::app()->cache->get('aFriends' . $id);
	if ($friends === false) {
	    $friends = array();
	    $aFriends = Yii::app()->db->createCommand('SELECT u.username, u.email, u.avatar FROM {{friends}} AS fr 
							JOIN {{users}} AS u
							ON fr.friend_user_id = u.user_id
							WHERE fr.user_id=' . user()->id)->queryAll();
	    foreach ($aFriends as $aFriends) {
		$friends[$aFriends['username']] = $aFriends['username'];
	    }
	    Yii::app()->cache->set('aFriends' . $id, $friends);
	}
	return $friends;
    }

}

